$(document).ready(function() {
    // IndexedDB初始化
    let db;
    const dbName = 'ForumDB';
    const dbVersion = 1;
    let COMMENTS_PER_PAGE = 10;
    let currentPage = 1;
    let totalPages = 1;
    let currentUser = null;

    // 随机用户名生成相关数据
    const adjectives = ['快乐的', '聪明的', '可爱的', '勇敢的', '温柔的', '活泼的', '善良的', '幽默的', '开朗的', '文静的'];
    const nouns = ['小猫', '小狗', '小兔', '小鸟', '小熊', '小鹿', '小象', '小狐狸', '小松鼠', '小企鹅'];
    const numbers = '0123456789';
    
    // 初始化数据库
    initDatabase();
    
    // 初始化事件绑定
    initEventHandlers();
    
    function initDatabase() {
        console.log('初始化论坛数据库');
        const request = indexedDB.open(dbName, dbVersion);
        
        request.onerror = function(event) {
            console.error('论坛数据库错误：', event.target.error);
        };
        
        request.onsuccess = function(event) {
            db = event.target.result;
            console.log('论坛数据库连接成功');
            loadComments();
        };
        
        request.onupgradeneeded = function(event) {
            db = event.target.result;
            if (!db.objectStoreNames.contains('comments')) {
                const store = db.createObjectStore('comments', { keyPath: 'id', autoIncrement: true });
                store.createIndex('timestamp', 'timestamp');
                store.createIndex('likes', 'likes');
                console.log('评论表创建成功');
            }
        };
    }

    // 生成随机用户名
    function generateRandomUsername() {
        const adjective = adjectives[Math.floor(Math.random() * adjectives.length)];
        const noun = nouns[Math.floor(Math.random() * nouns.length)];
        const number = Array.from({length: 4}, () => numbers[Math.floor(Math.random() * numbers.length)]).join('');
        return `${adjective}${noun}#${number}`;
    }
    
    function initEventHandlers() {
        console.log('初始化论坛事件绑定');
        
        // 论坛按钮点击事件
        $('.forum-btn').on('click', function() {
            console.log('论坛按钮点击');
            
            // 如果没有用户名，先弹出输入框
            if (!currentUser) {
                const username = prompt('请输入您的昵称（如不输入将随机生成）：');
                if (username === null) {
                    return; // 用户点击取消，不打开论坛
                }
                currentUser = username.trim() || generateRandomUsername();
            }
            
            const $btn = $(this);
            const $overlay = $('.forum-overlay');
            
            $btn.toggleClass('active');
            $overlay.css('display', 'flex').hide().fadeIn(300);
            $('body').css('overflow', 'hidden');
            
            // 显示用户名标签
            if ($('.username-badge').length === 0) {
                const $badge = createUsernameBadge();
                $('.comment-input-area').before($badge);
            } else {
                showUsernameBadge();
            }
            
            // 加载评论
            loadComments();
        });

        // 关闭按钮点击事件
        $('.forum-close-btn').on('click', function() {
            console.log('论坛关闭按钮点击');
            const $overlay = $('.forum-overlay');
            const $btn = $('.forum-btn');
            
            $overlay.fadeOut(300);
            $btn.removeClass('active');
            $('body').css('overflow', 'auto');
        });

        // 遮罩层点击事件
        $('.forum-overlay').on('click', function(e) {
            console.log('论坛遮罩层点击');
            if ($(e.target).hasClass('forum-overlay')) {
                $('.forum-close-btn').click();
            }
        });

        // 标签切换事件
        $('.tab-btn').on('click', function() {
            console.log('论坛标签切换');
            const $this = $(this);
            const tab = $this.data('tab');
            
            $('.tab-btn').removeClass('active');
            $this.addClass('active');
            
            if (tab === 'latest') {
                $('.comments-container').show();
                $('.hot-comments-ranking').hide();
                loadComments();
            } else {
                $('.comments-container').hide();
                $('.hot-comments-ranking').show();
                updateRanking();
            }
        });

        // 每页显示条数选择事件
        $('#commentsPerPage').on('change', function() {
            const value = $(this).val();
            if (value === 'custom') {
                $('.custom-page-size').show();
                // 将当前的条数填入输入框
                $('#customPageSize').val(COMMENTS_PER_PAGE);
            } else {
                $('.custom-page-size').hide();
                COMMENTS_PER_PAGE = parseInt(value);
                currentPage = 1; // 重置到第一页
                loadComments();
            }
        });

        // 自定义条数确定按钮点击事件
        $('#applyCustomPageSize').on('click', function() {
            const value = $('#customPageSize').val();
            const numValue = parseInt(value);
            
            if (!value || isNaN(numValue) || numValue < 1 || numValue > 100) {
                alert('请输入1-100之间的数字！');
                return;
            }
            
            COMMENTS_PER_PAGE = numValue;
            currentPage = 1; // 重置到第一页
            loadComments();
        });

        // 自定义条数输入框回车事件
        $('#customPageSize').on('keypress', function(e) {
            if (e.which === 13) { // 回车键
                $('#applyCustomPageSize').click();
            }
        });

        // 提交评论事件
        $('#submitComment').on('click', function() {
            console.log('提交评论按钮点击');
            const content = $('#commentContent').val().trim();
            
            if (!content) {
                alert('请输入评论内容！');
                return;
            }
            
            const comment = {
                content: content,
                username: currentUser,
                timestamp: new Date().getTime(),
                likes: 0
            };
            
            const transaction = db.transaction(['comments'], 'readwrite');
            const store = transaction.objectStore('comments');
            
            store.add(comment).onsuccess = function() {
                $('#commentContent').val('');
                loadComments();
                updateRanking();
            };
        });

        // 分页事件
        $('.prev-page').on('click', function() {
            console.log('上一页按钮点击');
            if (currentPage > 1) {
                currentPage--;
                loadComments();
            }
        });
        
        $('.next-page').on('click', function() {
            console.log('下一页按钮点击');
            if (currentPage < totalPages) {
                currentPage++;
                loadComments();
            }
        });

        // ESC键关闭论坛
        $(document).on('keydown', function(e) {
            if (e.key === 'Escape' && $('.forum-overlay').is(':visible')) {
                $('.forum-close-btn').click();
            }
        });

        // 重新生成用户名按钮点击事件
        $(document).on('click', '.regenerate-username', function() {
            const username = prompt('请输入您的昵称（如不输入将随机生成）：');
            if (username !== null) {
                currentUser = username.trim() || generateRandomUsername();
                showUsernameBadge();
            }
        });
    }

    // 创建用户名标签
    function createUsernameBadge() {
        return $(`
            <div class="username-badge">
                <span>当前昵称：</span>
                <span class="current-username">${currentUser}</span>
                <button class="regenerate-username" title="重新生成昵称">
                    <i class="fas fa-sync-alt"></i>
                </button>
            </div>
        `);
    }

    // 显示用户名标签
    function showUsernameBadge() {
        const $currentUsername = $('.current-username');
        if ($currentUsername.length) {
            $currentUsername.text(currentUser);
        } else {
            const $badge = createUsernameBadge();
            $('.comment-input-area').before($badge);
        }
    }

    // 加载评论
    function loadComments() {
        console.log('加载评论');
        const transaction = db.transaction(['comments'], 'readonly');
        const store = transaction.objectStore('comments');
        const index = store.index('timestamp');
        
        const comments = [];
        let count = 0;
        
        index.openCursor(null, 'prev').onsuccess = function(event) {
            const cursor = event.target.result;
            if (cursor) {
                count++;
                if (count > (currentPage - 1) * COMMENTS_PER_PAGE && count <= currentPage * COMMENTS_PER_PAGE) {
                    comments.push(cursor.value);
                }
                cursor.continue();
            } else {
                totalPages = Math.ceil(count / COMMENTS_PER_PAGE);
                displayComments(comments);
                updatePagination();
            }
        };
    }

    // 显示评论
    function displayComments(comments) {
        console.log('显示评论');
        const $commentsList = $('#commentsList');
        $commentsList.empty();
        
        comments.forEach(comment => {
            const $commentItem = $(`
                <div class="comment-item" data-id="${comment.id}">
                    <div class="comment-header">
                        <span class="comment-username">${comment.username || '匿名用户'}</span>
                        <span class="comment-time">${formatTime(comment.timestamp)}</span>
                    </div>
                    <div class="comment-content">${escapeHtml(comment.content)}</div>
                    <div class="comment-footer">
                        <button class="like-btn ${comment.liked ? 'liked' : ''}" data-id="${comment.id}">
                            <i class="fas fa-thumbs-up"></i>
                            <span class="like-count">${comment.likes}</span>
                        </button>
                    </div>
                </div>
            `);
            
            // 点赞按钮事件
            $commentItem.find('.like-btn').on('click', function() {
                console.log('点赞按钮点击');
                const $this = $(this);
                const commentId = $this.data('id');
                
                const transaction = db.transaction(['comments'], 'readwrite');
                const store = transaction.objectStore('comments');
                
                store.get(commentId).onsuccess = function(event) {
                    const comment = event.target.result;
                    comment.likes = (comment.likes || 0) + 1;
                    comment.liked = true;
                    
                    store.put(comment).onsuccess = function() {
                        $this.addClass('liked');
                        $this.find('.like-count').text(comment.likes);
                        updateRanking();
                    };
                };
            });
            
            $commentsList.append($commentItem);
        });
    }

    // 更新分页信息
    function updatePagination() {
        console.log('更新分页信息');
        $('.current-page').text(currentPage);
        $('.prev-page').prop('disabled', currentPage === 1);
        $('.next-page').prop('disabled', currentPage === totalPages);
    }

    // 更新排行榜
    function updateRanking() {
        console.log('更新排行榜');
        const transaction = db.transaction(['comments'], 'readonly');
        const store = transaction.objectStore('comments');
        const index = store.index('likes');
        const comments = [];
        
        let cursorRequest = index.openCursor(null, 'prev');
        let count = 0;
        
        cursorRequest.onsuccess = function(event) {
            const cursor = event.target.result;
            if (cursor && count < 3) { // 限制只显示前3条
                comments.push(cursor.value);
                count++;
                cursor.continue();
            } else {
                displayRanking(comments);
            }
        };
    }

    // 显示排行榜
    function displayRanking(comments) {
        console.log('显示排行榜');
        const $rankingList = $('#rankingList');
        $rankingList.empty();
        
        comments.forEach((comment, index) => {
            const $rankingItem = $(`
                <div class="ranking-item" data-id="${comment.id}">
                    <div class="ranking-number">${index + 1}</div>
                    <div class="ranking-content">
                        <div class="ranking-header">
                            <span class="ranking-username">${comment.username || '匿名用户'}</span>
                            <span class="ranking-time">${formatTime(comment.timestamp)}</span>
                        </div>
                        <div class="ranking-text">${escapeHtml(comment.content)}</div>
                        <div class="ranking-footer">
                            <div class="ranking-likes">
                                <i class="fas fa-thumbs-up"></i>
                                <span>${comment.likes}</span>
                            </div>
                            <button class="expand-btn">
                                展开 <i class="fas fa-chevron-down"></i>
                            </button>
                        </div>
                    </div>
                </div>
            `);
            
            // 展开/收起评论内容
            $rankingItem.find('.expand-btn').on('click', function(e) {
                e.stopPropagation();
                const $btn = $(this);
                const $text = $btn.closest('.ranking-item').find('.ranking-text');
                const isExpanded = $text.hasClass('expanded');
                
                if (isExpanded) {
                    $text.removeClass('expanded expanding');
                    $btn.removeClass('expanded').html('展开 <i class="fas fa-chevron-down"></i>');
                } else {
                    $text.addClass('expanded expanding');
                    $btn.addClass('expanded').html('收起 <i class="fas fa-chevron-up"></i>');
                }
            });
            
            // 点击整个评论项也可以展开/收起
            $rankingItem.on('click', function() {
                $(this).find('.expand-btn').click();
            });
            
            $rankingList.append($rankingItem);
        });
    }

    // 工具函数：格式化时间
    function formatTime(timestamp) {
        const date = new Date(timestamp);
        const now = new Date();
        const diff = now - date;
        
        if (diff < 60000) { // 小于1分钟
            return '刚刚';
        } else if (diff < 3600000) { // 小于1小时
            return Math.floor(diff / 60000) + '分钟前';
        } else if (diff < 86400000) { // 小于1天
            return Math.floor(diff / 3600000) + '小时前';
        } else {
            return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
        }
    }

    // 工具函数：转义HTML
    function escapeHtml(text) {
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }
}); 